iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 2
1
自我挑戰組

golang leetcode 30天挑戰系列 第 2

golang leetcode 30天挑戰 second day challenge shuffle the array

  • 分享至 

  • xImage
  •  

golang leetcode 30天挑戰 second day challenge shuffle the array

題目解讀:

題目來源:

shuffle-the-array

原文:

Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].

Return the array in the form [x1,y1,x2,y2,...,xn,yn].

解讀:

給定一個正整數陣列nums 一個正整數n

符合以下條件

nums = [x1, x2,..., xn,y1,y2,...yn]

撰寫一個演算法

產生一個正整數陣列results

符合以下條件

results = [x1, y1, x2, y2, ....,xn,yn]

初步解法:

初步觀察:

給定一個正整數陣列nums

則這個n = nums.length/2

然後 把nums 分成 前半x 跟後半y

兩個array 在同步loop放置到新的array results

初步設計:

given an array nums

set n = half of the length nums

create an array results with length of 2n

loop for index 0 to n-1:

results[2*i] = nums[i]

results[2*i+1] = nums[n+i]

return results

my solution source code

shuffle the array

package shuffle_array

func shuffle(nums []int, n int) []int {
	numsLen := len(nums)
	ret := make([]int, numsLen)
	for idx := 0; idx < n; idx++ {
		ret[2*idx] = nums[idx]
		ret[2*idx+1] = nums[idx+n]
	}
	return ret
}

遇到的困難

pseudo code撰寫

一開始不習慣把pseudo code寫下來

因此 不太容易把自己的code做解析

golang table driven test不熟

對於table driven test還不太熟析

所以對於寫test還是耗費不少時間

我的github source code

測資的撰寫

package shuffle_array

import (
	"reflect"
	"testing"
)

func Test_shuffle(t *testing.T) {
	type args struct {
		nums []int
		n    int
	}
	tests := []struct {
		name string
		args args
		want []int
	}{
		{
			name: "Example1",
			args: args{
				nums: []int{2, 5, 1, 3, 4, 7},
				n:    3,
			},
			want: []int{2, 3, 5, 4, 1, 7},
		},
		{
			name: "Example2",
			args: args{
				nums: []int{1, 2, 3, 4, 4, 3, 2, 1},
				n:    4,
			},
			want: []int{1, 4, 2, 3, 3, 2, 4, 1},
		},
		{
			name: "Example3",
			args: args{
				nums: []int{1, 1, 2, 2},
				n:    2,
			},
			want: []int{1, 2, 1, 2},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := shuffle(tt.args.nums, tt.args.n); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("shuffle() = %v, want %v", got, tt.want)
			}
		})
	}
}

參考文章

golang test


上一篇
golang leetcode 30天挑戰賽 first day - running sum of 1d array
下一篇
# golang leetcode 30天挑戰 third day - kids-with-greatest-number-of-candies
系列文
golang leetcode 30天挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
看不清
iT邦新手 5 級 ‧ 2020-09-02 15:25:26

你好,

my solution source code

shuffle the array

這個連結點了會連到 404 的頁面

json_liang iT邦研究生 5 級 ‧ 2020-09-03 13:01:13 檢舉

感謝幫忙勘誤 剛剛看到 以修改 有錯誤 再請指正

我要留言

立即登入留言